package com.gateway.plugin.resilience4j.executor;

import com.gateway.plugin.resilience4j.config.Resilience4JConfig;
import com.gateway.plugin.resilience4j.factory.Resilience4JRegistryFactory;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.reactor.circuitbreaker.operator.CircuitBreakerOperator;
import reactor.core.publisher.Mono;

import java.util.Optional;
import java.util.function.Function;

/**
 * @program: api-gateway
 * @description:
 * @author: YuKai Fan
 * @create: 2025/2/24 10:22
 **/
public class CircuitBreakerExecutor implements Executor
{
    @Override
    public <T> Mono<T> run(Mono<T> toRun, Function<Throwable, Mono<T>> fallback, Resilience4JConfig conf) {
        CircuitBreaker circuitBreaker = Resilience4JRegistryFactory.circuitBreaker(conf.getId(), conf.getCircuitBreakerConfig());
        Mono<T> to = toRun.transformDeferred(CircuitBreakerOperator.of(circuitBreaker));
        return Optional.ofNullable(fallback)
                .map(to::onErrorResume)
                .orElse(to);
    }
}
